package leecode.q134;

public class Solution {
    int[] gas;
    int[] cost;
    int res = -1;
    int begin = 3;

    public int canCompleteCircuit(int[] gas, int[] cost) {
        this.gas = gas;
        this.cost = cost;
        for (int i = 0; i < gas.length; i++) {
            begin = i;
            if (canRunOver(i)) {
                break;
            }
        }
        return res;
    }

    private boolean canRunOver(int start) {
        int curOil = 0;
        boolean notFirst = false;
        while (gas[start] + curOil >= cost[start]) {
            curOil = gas[start] + curOil - cost[start];
            if (start == begin && notFirst) {
                res = start;
                return true;
            }
            notFirst = true;
            start++;
            if (start == gas.length) {
                start = 0;
            }
        }
        return false;
    }
}
